package city.spring.modules.consumptionItem.service.impl;

import city.spring.modules.consumptionItem.entity.ConsumptionItemsEntity;
import city.spring.modules.consumptionItem.repository.ConsumptionItemsRepository;
import city.spring.modules.consumptionItem.service.ConsumptionItemsService;
import city.spring.modules.consumptionItem.vo.ConsumptionItemsEntityVO;
import city.spring.utils.TreeDataUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ListMultimap;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Service：收费项目
 *
 * @author pxm
 * @date 2020-08-05 16:18:33
 */
@CacheConfig(cacheNames = {ConsumptionItemsServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Exception.class)
@Service
public class ConsumptionItemsServiceImpl extends ServiceImpl<ConsumptionItemsRepository, ConsumptionItemsEntity> implements ConsumptionItemsService {

    private final ConsumptionItemsRepository consumptionItemsRepository;

    public ConsumptionItemsServiceImpl(ConsumptionItemsRepository consumptionItemsRepository) {
        this.consumptionItemsRepository = consumptionItemsRepository;
    }

    @Override
    public void saveConsumptionItems(ConsumptionItemsEntity entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateConsumptionItems(ConsumptionItemsEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteConsumptionItems(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteConsumptionItems(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }


    @Override
    public BigDecimal ConsumptionItemsCount(String itemId, Integer quantity) {
        // 根据传入消费项目id，获取消费项目的信息，单价
        ConsumptionItemsEntity consumptionItemsEntity = getById(itemId);
        // 总价：单价×数量
        BigDecimal totalPrice = consumptionItemsEntity.getCost().multiply(BigDecimal.valueOf(quantity));
        // 返回总价
        return totalPrice;
    }

    @Override
    public List<ConsumptionItemsEntity> converterToTreeDatasource(@NonNull List<ConsumptionItemsEntity> rawDatasource, boolean loadParentEntity) {
        ListMultimap<String, ConsumptionItemsEntity> multimap;
        // 对整体进行排序
        rawDatasource.sort(Comparator.comparing(ConsumptionItemsEntity::getGmtCreate));
        multimap = TreeDataUtils.handlerTreeDatasource(rawDatasource, "",
                ConsumptionItemsEntity::getId, ConsumptionItemsEntity::getCategoryId,
                ConsumptionItemsEntity::getChildren, ConsumptionItemsEntity::setChildren);
        if (loadParentEntity) {
            return TreeDataUtils.loadTreeParents(multimap, "", lambdaQuery(),
                    ConsumptionItemsEntity::getId, ConsumptionItemsEntity::setChildren);
        }
        return new ArrayList<>(multimap.values());
    }

    @Override
    public Set<String> getChildrenIds(Set<String> parentIds) {
        Set<String> ids = new HashSet<>();
        if (parentIds.isEmpty()) {
            return ids;
        }
        List<ConsumptionItemsEntity> list = lambdaQuery()
                .in(ConsumptionItemsEntity::getCategoryId, parentIds)
                .list();
        if (list.isEmpty()) {
            return ids;
        }
        Set<String> childrenIds = list.stream().map(ConsumptionItemsEntity::getId).collect(Collectors.toSet());
        ids.addAll(childrenIds);
        ids.addAll(getChildrenIds(childrenIds));

        return ids;
    }

    @Override
    public List<ConsumptionItemsEntity> getCategoryListByPidAndIsroom(String categoryId) {
        return consumptionItemsRepository.getCategoryListByPidAndIsroom(categoryId);
    }

    @Override
    public ConsumptionItemsEntity getBedFee(String categoryId, String bedId) {
        return consumptionItemsRepository.getBedFee(categoryId, bedId);
    }

    @Override
    public IPage<ConsumptionItemsEntityVO> listPage(Page<? extends ConsumptionItemsEntity> page, Wrapper<? extends ConsumptionItemsEntity> wrapper) {
        return baseMapper.listPage(page, wrapper);
    }

}